package coroutines.flow

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking
import java.lang.Exception

class FlowTest {
}

fun main() {
    runBlocking {
        flow {
            for (i in 0..10) {
                kotlinx.coroutines.delay(1000)
                emit(i)
                println("Thread is ${Thread.currentThread().name}")

                if (i > 5)
                    throw Exception("2233娘")
            }
        }.transform {
            emit(this)
            emit("AAAA")
            emit("BBB")
        }.map {
            "+++"
        }.filter {
            it != "+++"
        }
            .onStart {
                println("Before start")
            }.onEach {
                println("every time")
            }.onCompletion {
                println("After end")
            }.catch { cause ->
                println("Error: is ${(cause as? Exception)?.message}")
            }
            .flowOn(Dispatchers.Default)
            /**
             * 冷流，消费才产生数据
             * */
            .collect { i ->
                println("i = $i")
            }

//        listOf("A","B", "C").asFlow().collect {
//            println("str = $it")
//        }
//
//        flowOf("哔哩哔哩", "22娘", "33娘").collect {
//            println("content = $it")
//        }
    }
}